package com.powernode.boss.common.exceptions;


import com.powernode.boss.common.enums.SysCode;
import com.powernode.boss.common.exceptions.type.SysException;
import com.powernode.boss.models.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;

import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

//全局异常处理器
@RestControllerAdvice
public class GlobalExceptionHandler {

    Logger logger = LoggerFactory.getLogger(SysException.class);
    @ExceptionHandler(SysException.class)
    public Result handleSysException(SysException ex){
        logger.error("SysException-{}",ex);
        return Result.fail(ex.getSysCode());
    }

    // Bean Validation
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result handleArgumentNotValid(MethodArgumentNotValidException ex){

        StringBuffer buffer = new StringBuffer();
        List<FieldError> fieldErrors = ex.getFieldErrors();
        fieldErrors.forEach(fl->{
            buffer.append("错误项目:[" + fl.getField() + "], 错误提示:[" + fl.getDefaultMessage() + "]")
                    .append("--------");
        });
        Result result = new Result();
        result.setCode(SysCode.REQUEST_PARAM_ERRER.getCode());
        result.setMsg(SysCode.REQUEST_PARAM_ERRER.getText()+":{"+buffer+"}");
        result.setData("");
        return result;
    }
}
